package com.mtw.bbs.mq;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.mtw.bbs.common.core.constant.BusinessObjectType;
import com.mtw.bbs.common.core.constant.MQConstant;
import com.mtw.bbs.common.core.dto.BaseMQDto;
import com.mtw.bbs.constant.ReplyConstant;
import com.mtw.bbs.reply.pojo.entity.ReplyInfo;
import com.mtw.bbs.reply.service.ReplyInfoService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;


/**
 * 点赞数量变化消息
 */
@Slf4j
@Component
@RequiredArgsConstructor
@RocketMQMessageListener(topic = MQConstant.LIKE_TOPIC, selectorExpression = BusinessObjectType.REPLY, consumerGroup = "${rocketmq.consumer.group}")
public class LikeReplyMQConsumerService implements RocketMQListener<BaseMQDto> {


    private final RedissonClient redissonClient;
    private final ReplyInfoService replyInfoService;


    // 监听到消息就会执行此方法
    @Override
    public void onMessage(BaseMQDto dto) {

        if (dto.getCount() == 0){
            return;
        }
        RLock lock = redissonClient.getLock(ReplyConstant.LOCK_REPLY_lIKE_PREFIX + dto.getObjectId());
        try {
            lock.lock();
            String str = dto.getCount()>0?" + "+dto.getCount():" - CAST( " + -dto.getCount() +" AS UNSIGNED)";
            UpdateWrapper<ReplyInfo> uw = new UpdateWrapper<>();
            uw.setSql("like_count = ( like_count"+ str +")");
            uw.lambda().eq(ReplyInfo::getId,dto.getObjectId());
            replyInfoService.update(uw);
            log.info("评论点赞MQ消费成功，{}",dto);
        }catch (Exception e){
            log.error("",e);
        }finally {
            lock.unlock();
        }

    }

}
